/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xhserver;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author trivo
 */
public class XHServerHandler extends SimpleChannelInboundHandler<String>{

    // variables
    private static final Logger logger = Logger.getLogger(XHServerHandler.class.getName());
    
    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    // Phương thức dùng để gửi và nhận message từ client
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        
    }
    
    // Phương thức này được gọi khi kết nối đến client
    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( 
                new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                ctx.writeAndFlush("Welcome to XHServer");
                channels.add(ctx.channel());
            }
        });
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.log(Level.WARNING, "ServerHandler exception caught: ", cause);
        ctx.close();
    }
    
    
}
